<?php
namespace app\controller;

use app\model\EsModel;
use app\BaseController;

class Index extends BaseController
{
    public function index()
    {
        return view();
    }

    public function add()
    {
        if (!$this->request->isAjax()) {
            return '非法操作';
        }
        $table = 'add';
        $data = ['id' => '202201183231', 'name' => '贺强', 'age' => 34, 'sex' => '男', 'ctime' => 1642491072];
        $res = EsModel::insert($table, $data);
        if (!$res) {
            return ['code' => 1, 'message' => '添加失败'];
        }
        return ['code' => 0, 'message' => '添加成功'];
    }

    public function addAll()
    {
        if (!$this->request->isAjax()) {
            return '非法操作';
        }
        $data = [['name' => '贺强', 'age' => 34, 'sex' => '男', 'ctime' => 1642491072], ['name' => '周婷', 'age' => 30, 'sex' => '女', 'ctime' => 1642491072], ['name' => '贺周阳', 'age' => 1, 'sex' => '男', 'ctime' => 1642491072]];
        $res = EsModel::insertAll($data);
        if (!$res) {
            return ['code' => 1, 'message' => '添加失败'];
        }
        return ['code' => 0, 'message' => '添加成功'];
    }

    public function del()
    {
        if (!$this->request->isAjax()) {
            return '非法操作';
        }
        $table = 'add';
        $id = '202201183231';
        $res = EsModel::delete($table, $id);
        if (empty($res['_shards']) || empty($res['_shards']['successful'])) {
            return ['code' => 1, 'message' => '删除失败'];
        }
        return ['code' => 0, 'message' => '删除成功'];
    }

    public function getList()
    {
        if (!$this->request->isAjax()) {
            return '非法操作';
        }
        $table = 'add';
        $condition = [];
        $list = EsModel::getData($table, $condition);
        return $list;
    }
}
